'use client'

import { useEffect, useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Users, Shield, Database, Activity } from 'lucide-react'

interface AdminStats {
  totalUsers: number
  activeUsers: number
  totalRoles: number
  systemInfo: {
    version: string
    uptime: string
    lastBackup: string
  }
}

interface User {
  id: number
  username: string
  full_name: string
  role_name: string
  is_active: boolean
  created_at: string
}

interface Role {
  id: number
  name: string
  code: string
  description: string
}

export default function AdminDashboard() {
  const [stats, setStats] = useState<AdminStats | null>(null)
  const [recentUsers, setRecentUsers] = useState<User[]>([])
  const [roles, setRoles] = useState<Role[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    loadDashboardData()
  }, [])

  const loadDashboardData = async () => {
    try {
      // 获取用户数据
      const usersResponse = await fetch('/api/admin/users')
      const usersData = await usersResponse.json()

      // 获取角色数据
      const rolesResponse = await fetch('/api/admin/roles')
      const rolesData = await rolesResponse.json()

      if (usersData.success && rolesData.success) {
        const users = usersData.data
        const roles = rolesData.data

        // 计算统计信息
        const totalUsers = users.length
        const activeUsers = users.filter((user: User) => user.is_active).length

        setStats({
          totalUsers,
          activeUsers,
          totalRoles: roles.length,
          systemInfo: {
            version: '1.0.0',
            uptime: '7天 12小时',
            lastBackup: '2024-01-15 10:30:00'
          }
        })

        // 获取最近创建的用户
        const sortedUsers = users
          .sort((a: User, b: User) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
          .slice(0, 5)
        setRecentUsers(sortedUsers)

        setRoles(roles)
      }
    } catch (error) {
      console.error('加载管理面板数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="animate-pulse">
          <div className="h-8 bg-gray-200 rounded w-1/4 mb-6"></div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            {[1, 2, 3, 4].map(i => (
              <div key={i} className="h-32 bg-gray-200 rounded"></div>
            ))}
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">管理概览</h1>
        <p className="text-gray-600">系统管理和监控面板</p>
      </div>

      {/* 统计卡片 */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center">
                <div className="p-2 bg-blue-100 rounded-lg">
                  <Users className="h-6 w-6 text-blue-600" />
                </div>
                <div className="ml-4">
                  <p className="text-sm font-medium text-gray-600">总用户数</p>
                  <p className="text-2xl font-bold text-gray-900">{stats.totalUsers}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center">
                <div className="p-2 bg-green-100 rounded-lg">
                  <Activity className="h-6 w-6 text-green-600" />
                </div>
                <div className="ml-4">
                  <p className="text-sm font-medium text-gray-600">活跃用户</p>
                  <p className="text-2xl font-bold text-gray-900">{stats.activeUsers}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center">
                <div className="p-2 bg-purple-100 rounded-lg">
                  <Shield className="h-6 w-6 text-purple-600" />
                </div>
                <div className="ml-4">
                  <p className="text-sm font-medium text-gray-600">角色数量</p>
                  <p className="text-2xl font-bold text-gray-900">{stats.totalRoles}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center">
                <div className="p-2 bg-orange-100 rounded-lg">
                  <Database className="h-6 w-6 text-orange-600" />
                </div>
                <div className="ml-4">
                  <p className="text-sm font-medium text-gray-600">系统版本</p>
                  <p className="text-2xl font-bold text-gray-900">{stats.systemInfo.version}</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 最近用户 */}
        <Card>
          <CardHeader>
            <CardTitle>最近创建的用户</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {recentUsers.map((user) => (
                <div key={user.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <div>
                    <div className="font-medium text-gray-900">{user.full_name}</div>
                    <div className="text-sm text-gray-500">@{user.username}</div>
                  </div>
                  <div className="text-right">
                    <Badge variant={user.is_active ? "default" : "secondary"}>
                      {user.role_name}
                    </Badge>
                    <div className="text-xs text-gray-500 mt-1">
                      {new Date(user.created_at).toLocaleDateString()}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* 角色概览 */}
        <Card>
          <CardHeader>
            <CardTitle>系统角色</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {roles.map((role) => (
                <div key={role.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <div>
                    <div className="font-medium text-gray-900">{role.name}</div>
                    <div className="text-sm text-gray-500">{role.description}</div>
                  </div>
                  <Badge variant="outline">{role.code}</Badge>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 系统信息 */}
      {stats && (
        <Card>
          <CardHeader>
            <CardTitle>系统信息</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div>
                <div className="text-sm font-medium text-gray-600">系统版本</div>
                <div className="text-lg font-semibold text-gray-900">{stats.systemInfo.version}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-gray-600">运行时间</div>
                <div className="text-lg font-semibold text-gray-900">{stats.systemInfo.uptime}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-gray-600">最后备份</div>
                <div className="text-lg font-semibold text-gray-900">{stats.systemInfo.lastBackup}</div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
